<?php
header( "Content-Type:text/html; charset=utf-8" );
require_once("config.inc.php");
require_once("weibo.class.php");
require_once("db.class.php");
ignore_user_abort();
set_time_limit(0);
$wb = new weibo(APP_KEY, SECRET_KEY);
$wb->setUser( USER_NAME , USER_PASS );

$db = new db($site_Db);
//取出已处理最大ID
$last_tid = $db->fetchone("SELECT value FROM config WHERE var='last_tid'");
if( $ms = $wb->mentions($last_tid, 0, 20) )
{
	//更新最后处理微博ID
	$max = $ms[0]['id'];
	$db->query("UPDATE config SET value='{$max}' WHERE var='last_tid'");

	$ms=array_reverse($ms);
	foreach( $ms as $item )
	{
		$tid = $item['id'];
		$uid = $item['user']['id'];
		$uname = $item['user']['screen_name'];
		//只处理固定格式
		preg_match("/^(.+?)@时间助手\s?$/u", trim($item['text']), $match);
		$text = trim($match[1]);
		if(!empty($text)) {
			$command = explode(' ',$text);
			$type = $command[0];
			$data = trim($command[1]);
			if(!empty($type) && in_array($type, $option_array)) {
				//此条insert可以考虑通过批量插入优化
				if($db->query("INSERT INTO request VALUES(null, '{$tid}', '{$uid}', '{$uname}', '{$type}', '{$data}', ".time().", 0)"))
				echo "Add a request.\n";
			}
		} else {
			echo "No matched.\n";
		}
	}
	//暂停3秒后执行
	sleep(3);
	@exec('/usr/local/php5/bin/php -f /usr/local/www/weibo/shijian/handle_request.php');
} else {
	echo "No mentions.\n";
}

$db->close();

?>